package com.cn.wanxi.dao.impl;

import com.cn.wanxi.dao.ProductDao;
import com.cn.wanxi.model.ProductModel;
import com.cn.wanxi.util.JDBC;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class ProductImpl implements ProductDao {
    @Override
    public List<ProductModel> findAll(ProductModel productModel) {
        StringBuilder sql = new StringBuilder();
        sql.append("select p.*,c.name cuisineName from product p,cuisine c  \n" +
                "where p.cuisine_id=c.id \n" +
                "order by p.id desc");
        sql.append(" limit  " + (productModel.getPageModel().getCurPage() - 1) * productModel.getPageModel().getPageSize() + "," + productModel.getPageModel().getPageSize() + "");
        ResultSet resultSet = JDBC.query(sql.toString());
        List<ProductModel> list = new ArrayList<>();
        try {
            while (resultSet.next()) {
                ProductModel model = new ProductModel();
                model.setId(resultSet.getInt("id"));
                model.setName(resultSet.getString("name"));
                model.setContent(resultSet.getString("content"));
                model.setCuisineName(resultSet.getString("cuisineName"));
                model.setIsShow(resultSet.getInt("is_show"));
                model.setPrice(resultSet.getFloat("price"));
                model.setImgHref(resultSet.getString("img_href"));
                list.add(model);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

    @Override
    public int getCount(ProductModel productModel) {
        String sql = "select count(*) count  from product p,cuisine c  \n" +
                "where p.cuisine_id=c.id \n" +
                "order by p.id desc";
        ResultSet resultSet = JDBC.query(sql);
        try {
            while (resultSet.next()) {
                return resultSet.getInt("count");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public int add(ProductModel productModel) {
        String sql="insert into product()values()";
        return JDBC.update(sql);
    }
}
